<?php
/**
 * Model Bill
 * @package Model
 * @author chinhpv.hp
 */

class Model_Bill extends Zend_Db_Table_Abstract{
	protected $_name = 'bill';
	protected $_dependTables = array("Model_BillProduct");
	protected $db ;
	
	/**
	 * Đếm tổng số bill
	 * @return int total bill
	 */
	function countBill(){
		$select = $this->_db->select()->from('bill',array("COUNT(bill.id) as total"));
		 return $this->_db->fetchOne($select);
	}
	/**
	 * Đếm số lượng bill có readed là 0
	 */
	function countBillUnReaded(){
		 $select = $this->_db->select()->from('bill',array("COUNT(bill.id) as total"))->where("readed = 0");
		 return $this->_db->fetchOne($select);
	}
	/**
	 * tạo bill mới
	 * @param string cus_name
	 * @param string cus_email
	 * @param string cus_phone
	 * @param string cus_address
	 * @return int id_bill 
	 */
	function addBill($cus_name,$cus_email,$cus_phone,$cus_address)
	{
		$bill = $this->createRow();
		$bill->cus_name = $cus_name;
		$bill->cus_email = $cus_email;
		$bill->cus_phone = $cus_phone;
		$bill->cus_address = $cus_address;
		$bill->readed = 0;
		$bill->save();
		
		try {
			$bill_id = $this->_db->lastInsertId();
			return $bill_id;
		}catch (Exception $e){
			echo $e->getMessage();
		}
	
		
	}
	
	/**
	 * 
	 * get all bill
	 * @return Zend_Db_Table_Row
	 */
	public function getAllBill(){
	$db = $this->_db;	
	$select = $db->select()->from(array('bp' => 'bill_product'))
             ->joinLeft(array('b' => 'bill'),
                    'b.id = bp.bill_id')
             ->joinLeft(array('p' => 'product'), 'bp.product_id = p.id', array('sum(bp.quantity*p.price) as totalprice'))
             ->group('b.id');
             
    $stmt = $select->query();
	$result = $stmt->fetchAll();
	return $result;
	}
	/**
	 * get bill by bill_id
	 */
	public function getBillByID($id){
		$db = $this->_db;	
		$select = $db->select()->from(array('bp' => 'bill_product'))
             ->joinLeft(array('b' => 'bill'),
                    'b.id = bp.bill_id')
             ->joinLeft(array('p' => 'product'), 'bp.product_id = p.id', array('name','price','speed','ink'))
             ->where('b.id = '.$id);
             
             
   		$stmt = $select->query();
		$result = $stmt->fetchAll();
		return $result;
	}
	
	/**
	 * update trường readed
	 * @param int $id
	 */
	public function updateReaded($id){
		$data = array('readed'=> 1);
		return $this->update($data, 'id = '.$id);
	}
	
	/**
	 * 
	 * xóa bill theo id
	 * @param string $id
	 */
	public function deleteByID($id){
		
	if(is_numeric($id)){
			
				
			return $this->delete('id='.$id);
		}else{
			
			return $this->delete('id in ('.$id.')');
		}
	}
}